package com.mfnote.view.record;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mfnote.adapter.NewRecordAdapter;
import com.mfnote.db.dao.RecordDao;
import com.mfnote.model.RecordEntity;
import com.mfnote.util.FinalData;
import com.mfnote.util.TimeUtil;
import com.mfnote.view.R;
import com.mfnote.view.R.anim;
import com.mfnote.view.R.drawable;
import com.mfnote.view.R.id;
import com.mfnote.view.R.layout;
import com.mfnote.view.other.MyApplication;

/**
 * 录音界面
 * @author DC
 *
 */
public class NewRecordActivity extends Activity implements OnItemClickListener, OnClickListener {
	// 输入文件名
	private EditText newrecord_record_name_et = null;
	//录音时的LinearLayout
	private LinearLayout newrecord_start_ll = null;
	// 录音和播放时的动画一样
	private ImageView newrecord_record_play_iv = null;
	//录音或者是放音
	private Button newrecord_record_bt = null;
	//显示录音的时长
	private TextView newrecord_record_time_tv = null;
	//放音时的LinearLayout
	private LinearLayout newrecord_play_ll = null;
	//播放录音按钮
	private Button newrecord_play_bt = null;
	//录音进度条
	private ProgressBar newrecord_play_pb = null;
	//显示已经播放的时长
	private TextView newrecord_play_start_tv = null;
	//录音文件的总时长
	private TextView newrecord_play_end_tv = null;
	//加载底部菜单
	private GridView newrecord_bottom_gv = null;
	//记录录音开始时间
	private long recordtime_start = 0;
	//记录录音总时长
	private long recordTotalTimeLong = 0 ;
	//是否通知主线程更新显示的时间
	private boolean isRunRecordTime = true;
	//是否已经开始录音或播放
	private boolean isStart = true;
	//进度条线程
	private boolean isProgressBarRun = true;
	//当前已播放的进度
	private int progressValue = 0;
	//是否在播放状态
	private boolean isPlayOver = true;
	//播放录音，暂停播放状态
	private boolean isPlayPause =true;
	//录音动画
	private AnimationDrawable recordAnimation = null;
	//放音动画
	private AnimationDrawable playAnimation = null;
	//录音文件
	private File file = null;
	//录音
	private MediaRecorder mediaRecorder = null;
	//放音
	private MediaPlayer mediaPlayer = null;
	//保存录音的文件夹
	private File destDir =null;
	//录音文件是否保存
	private boolean isRecordSave = false;
	//记录当前的文件名
	private String currentFileName;
	//当前的时间值
	private String timeNow;
	//记录录音文件的属性
	private HashMap<String,Object> map =null;
	//录音文件的原文件名
	private String oldFileName;
	
	private AudioManager mAudioManager  = null;
	//当前音量的比例
	private int currentVolumNum = 100;
	//手机最大音量
	private float maxVolume =0;;
	AlertDialog alertDlgExit;  //提示保存对话框
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 20:
				//获得当前时间
				long currentTime =System.currentTimeMillis();
				if(currentTime>recordtime_start){
					recordTotalTimeLong =(currentTime-recordtime_start)/1000;
					//显示当前已录音的时长
					newrecord_record_time_tv.setText(TimeUtil.getRecordTime(recordTotalTimeLong));
				}
				break;
			case 21:
				//进度条走
				newrecord_play_pb.setProgress(msg.arg1);
				//显示已播放的时长
				newrecord_play_start_tv.setText(TimeUtil.getPlayTime(msg.arg1));
				newrecord_bottom_gv.setFocusable(true);
				isPlayOver = false;
            	isPlayPause =true;
				if(msg.arg1==recordTotalTimeLong){
					//1.停止录音动画，放音动画播放
					stopPlayAnimation();
					//2.播放按钮切换成play状态
					newrecord_play_bt.setBackgroundResource(R.drawable.newrecord_btn_play_selector);
					//3.newrecord_play_start_tv的值设为00:00
					newrecord_play_start_tv.setText("00:00");
					//4.进度条值progressValue = 0
					progressValue = 0;
					//5.停止播放录音
					if(mediaPlayer!=null){
						mediaPlayer.stop();
						mediaPlayer.release();
						mediaPlayer = null;
					}
					//6.不再是播放状态
					isPlayOver =true;
					isPlayPause =false;
				}
			}
		}
		
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newrecord);
		mAudioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
		//获得最大音量
		maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		MyApplication.getInstance().addActivity(this);
		loadAllWedgit();	
		map = (HashMap<String, Object>) this.getIntent().getSerializableExtra("map");
	    if(map!=null){
	    	isRecordSave = true;
	    	Log.d("map1", map.get("recordPath").toString());
	    	getCurrentRecord();
	    }	
	
	}
	
	/**获得所有的控件及添加监听事件**/
	private void loadAllWedgit(){
		newrecord_bottom_gv = (GridView) this.findViewById(R.id.newrecord_bottom_gv);
		newrecord_bottom_gv.setSelector(new ColorDrawable(Color.TRANSPARENT));  //去掉自身自带的按下背景效果
		newrecord_record_name_et = (EditText) this.findViewById(R.id.newrecord_record_name_et);

	
		newrecord_start_ll = (LinearLayout) this.findViewById(R.id.newrecord_start_ll);
		newrecord_play_ll = (LinearLayout) this.findViewById(R.id.newrecord_play_ll);
	
		newrecord_record_time_tv = (TextView) this.findViewById(R.id.newrecord_record_time_tv);
		newrecord_record_bt =  (Button) this.findViewById(R.id.newrecord_record_bt);
		newrecord_record_play_iv = (ImageView) this.findViewById(R.id.newrecord_record_play_iv);
	
		
		
		newrecord_record_time_tv.setText("00:00");
		
		newrecord_record_bt.setOnClickListener(this);
		newrecord_bottom_gv.setAdapter(new NewRecordAdapter(this));
		newrecord_bottom_gv.setOnItemClickListener(this);
		//newrecord_bottom_gv.setFocusable(false);
		
		//放音
		newrecord_play_bt = (Button) this.findViewById(R.id.newrecord_play_bt);
		newrecord_play_pb = (ProgressBar) findViewById(R.id.newrecord_play_pb);
		newrecord_play_start_tv = (TextView) findViewById(R.id.newrecord_play_start_tv);
		newrecord_play_end_tv = (TextView) findViewById(R.id.newrecord_play_end_tv);
		
	
	}
	
	/**获得当前的录音文件**/
	private void getCurrentRecord(){
	    oldFileName = map.get("title").toString();
		String oldRecordPath = map.get("recordPath").toString();
		int oldFileLength = Integer.valueOf(map.get("recordLength").toString());
	
		recordTotalTimeLong = oldFileLength;
		isPlayOver = true;
		isPlayPause = false;
		//设置录音键不可见
		newrecord_start_ll.setVisibility(View.GONE);
		//设置播音键可见
		newrecord_play_ll.setVisibility(View.VISIBLE);
		newrecord_play_bt.setOnClickListener(this);
		newrecord_play_start_tv.setText("00:00");
		
		newrecord_record_name_et.setText(oldFileName);
		newrecord_record_name_et.setSelection(oldFileName.length());
		File currentFile = new File(oldRecordPath);
		file =currentFile;
		playRecord();
		
		Log.d("newfilename", oldFileName+" "+file.getAbsolutePath()+" "+oldFileLength+" "+file.length());
	}
    
	/**监听ListView的点击事件**/
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		switch (position) {
		case 0:
			//Toast.makeText(this, "舍弃", Toast.LENGTH_SHORT).show();
			this.abandonRecord();
			break;
		case 1:
			this.saveRecord();
			break;
		case 2:
			if(recordTotalTimeLong<1){
				return;
			}
			  // Toast.makeText(this, "播放", 1).show();
			  //设置录音键不可见
			  newrecord_start_ll.setVisibility(View.GONE);
			  //设置播音键可见
			  newrecord_play_ll.setVisibility(View.VISIBLE);
			  newrecord_play_bt.setOnClickListener(this);
			  newrecord_play_start_tv.setText("00:00");
			  newrecord_play_end_tv.setText("00:44");
			  playRecord();		
			  break;
		case 3:
			  //Toast.makeText(this, "选择", Toast.LENGTH_SHORT).show();
			  boolean sdcardExist = Environment.getExternalStorageState().equals(
						android.os.Environment.MEDIA_MOUNTED);
			  if(!sdcardExist){
				  Toast.makeText(this, "未找到SD卡", Toast.LENGTH_SHORT).show();
			  }
			  int requestCode = FinalData.NEWHADNACTIVITY_REQUESTCODE;
			  Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
			  intent.setType("file/*");
			  Intent wrapperIntent = Intent.createChooser(intent, null);
			  startActivityForResult(wrapperIntent, requestCode);  
			break;

		}
	}

	/**舍弃当前状态的录音数据**/
	private void abandonRecord() {
        newrecord_record_name_et.setText("");
        //TODO进入录音状态
        newrecord_play_ll.setVisibility(View.GONE);
        newrecord_start_ll.setVisibility(View.VISIBLE);
        newrecord_record_time_tv.setText("00:00");
        newrecord_record_bt.setBackgroundResource(R.drawable.newrecord_btn_start_selector);
        newrecord_record_play_iv.setBackgroundResource(R.drawable.audio_0);
        
        progressValue = 0;
        recordTotalTimeLong = 0;
        isProgressBarRun = false;
        isPlayOver = true;
        isPlayPause =false;
        isRunRecordTime = false;
        isStart = true;
        if(mediaRecorder!=null){
        	mediaRecorder.stop();
        	mediaRecorder.release();
        	mediaRecorder = null;
        }
        if(mediaPlayer!= null){
        	mediaPlayer.stop();
        	mediaPlayer.release();
        	mediaPlayer = null;
        }
        if(playAnimation!=null){
        	stopPlayAnimation();
        }
        if(recordAnimation!=null){
        	stopRecordAnimation();
        }
	
        isRecordSave = false;
	}
    
	/**监听button的点击事件**/
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newrecord_record_bt:
			boolean sdcardExist = Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED);
			if(!sdcardExist){
				Toast.makeText(this, "SD卡未找到", Toast.LENGTH_SHORT).show();
				return;
			}
			if(isStart){
				//TODO 开始录音
				this.recordMedia();
				isRunRecordTime =true;	
				recordtime_start = System.currentTimeMillis();
				newrecord_record_bt.setBackgroundResource(R.drawable.newrecord_btn_pause_selector);
				try {
					new Thread(){
						@Override
						public void run() {
							while(isRunRecordTime){
								//通知主线程更新record时间
								Message msg = new Message();
								msg.what = 20;
								handler.sendMessage(msg);
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}						
						}
						
					}.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
				//播放录音动画
				this.playRecordAnimation();
				isStart = false ;
				
			}else{
				 stopRecord();
			}
			break;
		case R.id.newrecord_play_bt:
			if(recordTotalTimeLong<1){
				return;
			}
			 //放音处理
			 //TODO
			 //如果播放完成，则从头开始播放,否则是继续播放
             if(!isPlayOver){
            	 if(isPlayPause){
            		 //进入暂停状态
                	 //1.button为play状态
                	 newrecord_play_bt.setBackgroundResource(R.drawable.newrecord_btn_play_selector);
                     //2.动画停止
                	 this.stopPlayAnimation();
                	 //3.
                	 isProgressBarRun = false;
                	 isPlayPause = false;
                	 //进入暂停状态
                	 mediaPlayer.pause();
            	 }else{
            		 //继续播放
            		 //1.button为pause状态
                	 newrecord_play_bt.setBackgroundResource(R.drawable.newrecord_btn_pause_selector);
                     //2.动画停止
                	 this.playPlayAnimation();
                	 //3.
                	 progressValue-=0;
                	 isProgressBarRun = true;
                	 playRecord();
            	 }
             }else{
            	 //从头开始播放
            	 progressValue = 0;
            	 playRecord();
            	
             }
			break;
		}
	}
	
	/**停止录音**/
	private void stopRecord() {
		 //TODO 暂停录音
		 mediaRecorder.stop();
		 mediaRecorder.release();
		 mediaRecorder = null;
		 //Toast.makeText(this, "暂停录音", 1).show();
		 stopRecordAnimation();
		 //停止停止主线程更新record时间
		 isRunRecordTime= false;
		 newrecord_record_bt.setBackgroundResource(R.drawable.newrecord_btn_start_selector);
		 isStart = true ;
		 //录音暂停之后可以进行其他处理操作		
	}

	/**播放录音**/
	private void playRecord(){
		if(file.length()<1){
			Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
			//TODO 删除该条目
			RecordDao dao =new RecordDao(this);
			dao.deleteRecord(map);
			Intent no_file_intent = new Intent(this,RecordActivity.class);
			startActivity(no_file_intent);
			this.finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			return;
		}
		 newrecord_bottom_gv.setFocusable(false);
		 //1.按钮置成pause
		 newrecord_play_bt.setBackgroundResource(R.drawable.newrecord_btn_pause_selector);
		 //2.播放录音动画，放音动画
		 this.playPlayAnimation();
		 //TODO
		 //3.播放录音
		 if(!isPlayPause&&!isPlayOver){
			//继续播放
			mediaPlayer.start();
			

		 }else{
			//从头开始播放
			playMedia(); 
		 }
		//int maxVolum = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		
		 //4.通知主线程进度条开始,时间走
		 newrecord_play_pb.setMax((int)recordTotalTimeLong);
		 newrecord_play_end_tv.setText(TimeUtil.getPlayTime(recordTotalTimeLong));
		 //子线程run方法执行
		 isProgressBarRun =true;
		 try {
			new Thread(){
			  
				@Override
				public void run() {
					while(isProgressBarRun){
						Message msg = new Message();
						msg.what = 21;
						msg.arg1 = progressValue++;
						//进度条已走完,也就是播放完了
						if(progressValue>=(int)recordTotalTimeLong+1){
							//TODO
							//5.isProgressBarRun置为false
							isProgressBarRun = false;
							
						}
						handler.sendMessage(msg);
						
							try {
								Thread.sleep(1000);
							} catch (Exception e) {
								e.printStackTrace();
							}
					}
				}
				 
			 }.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
		 
	}

	/**停止放音动画 **/
	private void stopPlayAnimation(){
		stopRecordAnimation();
		if(playAnimation!=null){
			playAnimation.stop();
			playAnimation = null;
		}
		newrecord_record_play_iv.setBackgroundResource(R.drawable.audio_0);
	}
	
	/**停止录音动画**/
	private void stopRecordAnimation(){
		if(recordAnimation!=null){
			//录音动画停止
			 recordAnimation.stop();
			 recordAnimation =null;
		}
		 //将图片设置成正常状态的
		newrecord_record_play_iv.setBackgroundResource(R.drawable.audio_0);
	}
	
	/**播放录音动画**/
	private void playRecordAnimation(){
		//TODO 将录音的newrecord_record_iv设置可见
		newrecord_record_play_iv.setVisibility(View.VISIBLE);
		newrecord_record_play_iv.setBackgroundResource(R.anim.mic);
		recordAnimation =(AnimationDrawable) newrecord_record_play_iv.getBackground();
		recordAnimation.start();
	}
	
	/**播放放音动画**/
	private void playPlayAnimation(){
		//TODO 将放音的newrecord_play_iv设置可见
		newrecord_record_play_iv.setVisibility(View.VISIBLE);
		newrecord_record_play_iv.setBackgroundResource(R.anim.mic);
		playAnimation =(AnimationDrawable) newrecord_record_play_iv.getBackground();
		playAnimation.start();
	}
	
	/**开始录音**/
	private void recordMedia(){
		try {
			createFile();
			currentFileName = createFileName();
			file = new File(destDir.getAbsolutePath()+"/"+currentFileName);
			mediaRecorder = new MediaRecorder();
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
			mediaRecorder.setOutputFile(file.getAbsolutePath());
			mediaRecorder.prepare();
			mediaRecorder.start();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	/**播放录音**/
	private void playMedia(){
		try {
			mediaPlayer = new MediaPlayer();
			Log.d("file", file.getAbsolutePath());
			mediaPlayer.setDataSource(file.getAbsolutePath());
			mediaPlayer.prepare();
			recordTotalTimeLong = mediaPlayer.getDuration()/1000;
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
    
	/**保存录音**/
	private void saveRecord(){
		RecordDao dao =new RecordDao(this);
		//TODO 保存到数据库,跳转到RecordActivity
		RecordEntity recordEntity  =new RecordEntity();
		if(isRecordSave){
			String name = newrecord_record_name_et.getText().toString();
			if(name.equals(oldFileName)){
				Toast.makeText(this, "文件已保存", Toast.LENGTH_SHORT).show();
				return;
			}else{
				long state = dao.queryRecord(name);
				if(state>0){
				   //数据库中存在该title,不保存,提示用户
				   Toast.makeText(this, "该用户名已存在，请重新输入", Toast.LENGTH_SHORT).show();
				   return ;
				}
				recordEntity.setTitle(name);
				recordEntity.setTimeNow(timeNow);
				if(destDir==null){
					createFile();
				}
				Log.d("FILE", name+" "+oldFileName);
				File newfile = new File(destDir.getAbsolutePath()+"/"+name+".amr");
				File oldFile = new File(destDir.getAbsolutePath()+"/"+oldFileName+".amr");
				file.renameTo(oldFile);
				file.renameTo(newfile);
				file = newfile;
				
			}
		}else{
			if(recordTotalTimeLong<1){
				Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
				return ;
			}
			
			if(!isPlayOver){
				return ;
			}
		
			if(!isStart){
				Toast.makeText(this, "正在录音", Toast.LENGTH_SHORT).show();
				return ;
			}

			Log.d("old_filename", file.getName()+file.getAbsolutePath()+recordTotalTimeLong);
			
			String name = newrecord_record_name_et.getText().toString();
			
			if(name==null||name.trim().equals("")||name==""){
				Log.d("==", file.getName());
				String title = file.getName().substring(0, file.getName().length()-4);
				recordEntity.setTitle(title);
				recordEntity.setTimeNow(timeNow);
			}else{
				recordEntity.setTitle(name);
				recordEntity.setTimeNow(timeNow);
				File temp=new File(destDir.getAbsolutePath()+"/"+name+".amr");
				file.renameTo(temp);
				file.delete();
				file = temp;
			}
		}
		recordEntity.setSize(file.length());
		recordEntity.setRecordLength((int)recordTotalTimeLong);
		recordEntity.setRecordPath(file.getAbsolutePath());
		long state = dao.insertRecord(recordEntity);
		if(state>0){
			//保存成功,跳转
			Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(this,RecordActivity.class);
			startActivity(intent);
			this.finish();
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
		}else{
			Toast.makeText(this, "保存出错", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	/**获得SD开的路径**/
	private String getSDCardPath() {
		String sdcardDir = null;
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) { // 判断是否有SD卡
			sdcardDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
		} else {
			Toast.makeText(this, "没有找到SD卡", Toast.LENGTH_SHORT).show();
		}

		return sdcardDir;
	}
	
	/**创建录音文件的保存位置**/
	private void createFile(){
		destDir = new File(getSDCardPath() + "/MFNote/record");
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
	}
	
	/**获得一个时间值的文件名**/
	private String createFileName() {
		String fileName = "";
		Date date = new Date(System.currentTimeMillis());  //系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
		fileName = dateFormat.format(date)+".amr";
		dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		timeNow = dateFormat.format(date);
		return fileName;
	}

	/**监听返回键及音量键**/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			Log.d("down", isRecordSave+" "+recordTotalTimeLong+" "+isStart);
			if(!isRecordSave&&recordTotalTimeLong>0&&!isStart){
				Log.d("stop", "stopRecord");
				//停止录音
				stopRecord();
				//提示是否保存
				openExitDialog();
				//loadIsSave();
			}else if(!isRecordSave&&recordTotalTimeLong>0){
				//提示是否保存
				//loadIsSave();
				openExitDialog();
			}else {
				if(mediaPlayer!=null){
					mediaPlayer.release();
					mediaPlayer = null;
				}
				//直接跳转
				Intent intent = new Intent(NewRecordActivity.this,RecordActivity.class);
				startActivity(intent);
				this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			}
			break;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			currentVolumNum-=5;
			if(currentVolumNum<=0){
				currentVolumNum = 0;
			}
			//设置当前音量
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(maxVolume * currentVolumNum / 100), 0);
			break;
		case KeyEvent.KEYCODE_VOLUME_UP:
			currentVolumNum+=5;
			if(currentVolumNum>=100){
				currentVolumNum = 100;
			}
			//设置当前音量
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int)(maxVolume * currentVolumNum / 100), 0);
			break;
		}
		//int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		return true;
	}
    
	/**未保存弹出对话框提示是否保存**/
	/**是否保存录音的对话框**/
	private void openExitDialog() {
		LayoutInflater inflater=LayoutInflater.from(this);
		View viewDialog=inflater.inflate(R.layout.dialog_issave_remind, null);
		alertDlgExit = new AlertDialog.Builder(this).create();
		alertDlgExit.show();
		Display display=this.getWindowManager().getDefaultDisplay();
		int width=display.getWidth();
		int height=display.getHeight();
		LayoutParams layoutParams=new LayoutParams(width*90/100,LayoutParams.WRAP_CONTENT);	
		alertDlgExit.setContentView(viewDialog, layoutParams);
//		alertDlgExit = new AlertDialog.Builder(this).create();
//		alertDlgExit.show();
//		Window window = alertDlgExit.getWindow();
//		window.setContentView(R.layout.newwrite_exit_dialog);
		Button sure_btn = (Button) viewDialog.findViewById(R.id.sure_btn);
		Button cancel_btn = (Button) viewDialog.findViewById(R.id.cancel_btn);
		sure_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//保 存录音文件
			    saveRecord();
			    alertDlgExit.dismiss();
			}
		});
		cancel_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDlgExit.dismiss();
				//跳转
				Intent intent =new Intent(NewRecordActivity.this,RecordActivity.class);
				startActivity(intent);
				NewRecordActivity.this.finish();
				overridePendingTransition(R.anim.push_left_in,
						R.anim.push_right_out);
			}
		});
	}
	
	/**Activity中的事件处理回调函数**/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode==FinalData.NEWHADNACTIVITY_REQUESTCODE){
			if(data==null){
				Toast.makeText(this, "未选择文件", Toast.LENGTH_SHORT).show();
				return;
			}
			Uri uri  = data.getData();
		   
			Log.d("data", "data");
			//获得所选文件的path
			String path = uri.getPath();
			if(!path.endsWith(".amr")){
				Toast.makeText(this, "您打开的文件不可播放", Toast.LENGTH_SHORT).show();
				return;
			}
			chooseFilePlay(path);
			Log.d("path", path);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**用户选择了录音文件之后,进入播放录音阶段**/
	private void chooseFilePlay(String path){
		   try {
			   String oldFileName = path.substring(path.lastIndexOf("/")+1, path.length()-4);
			   String oldRecordPath = path;
			   isRecordSave = true;
			   Log.d("oldRecordPath", oldRecordPath);
			   isPlayOver = true;
			   isPlayPause = false;
			   
				//设置录音键不可见   
				newrecord_start_ll.setVisibility(View.GONE);
				//设置播音键可见
				newrecord_play_ll.setVisibility(View.VISIBLE);
				newrecord_play_bt.setOnClickListener(this);
				newrecord_play_start_tv.setText("00:00");
				
				newrecord_record_name_et.setText(oldFileName);
				File currentFile = new File(oldRecordPath);
				file =currentFile;
				playRecord();
			   //TODO 对文件进行筛选,不能播放的弹Toast提示用户
			   Log.d("oldfilename", oldFileName+"  "+recordTotalTimeLong);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}